<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    //http://scriptoj.mangojuice.top/problems/52
    const app = {
      middlewares: [],
      callback(ctx) {
        console.log(ctx);
      },
      //中间件是一个函数，可以被传入一个 ctx 和 next
      //调用 next 的时候会执行下一个中间件,如果不调用 next 会阻止接下来所有的中间件的执行，也不会执行 app.callback
      use(fn) {
        this.middlewares.push(fn);
      },
      go(ctx) {
        let index = 0;
        const next = () => {
          index++;
        };

        this.middlewares.forEach((md, current) => {
          if (index === current) md(ctx, next);
        });

        index === this.middlewares.length && this.callback(ctx);
      }
    };

    app.use((ctx, next) => {
      ctx.name = "lucy";
      next();
    });

    app.use((ctx, next) => {
      ctx.age = 12;
      next();
    });

    app.use((ctx, next) => {
      console.log(`${ctx.name} is ${ctx.age} year old`);
      next();
    });

    app.go({});

    app.use((ctx, next) => {
      ctx.version = "10.0.0";
      next();
    });

    app.go({});
  </script>
</html>
